package com.activeMQ;

import javax.jms.Connection;
import javax.jms.ConnectionFactory;
import javax.jms.DeliveryMode;
import javax.jms.Destination;
import javax.jms.JMSException;
import javax.jms.MessageConsumer;
import javax.jms.MessageProducer;
import javax.jms.Session;
import javax.jms.TextMessage;

import org.apache.activemq.ActiveMQConnectionFactory;

/**
 * 消费者
 * @author gxkj-042
 *
 */
public class Receiver {

	public static void main(String[] args) throws JMSException{
		//建立ConnectionFactory工厂对象，需要填入用户名、密码、连接地址，默认地址：tcp://localhost:61616
		ConnectionFactory connectionFactory = new ActiveMQConnectionFactory(
				"zhangsan", 
				"password",
				"tcp://localhost:61616");

		//通过connectionFactory工厂对象创建connection连接，并用connection的start方法开启连接，
		//connection默认是关闭的
		Connection connection = connectionFactory.createConnection();
		connection.start();
		
		//通过connection创建session会话（上下文环境对象），用于接收消息，配置参数2为签收模式
		//Session session = connection.createSession(Boolean.FALSE, Session.AUTO_ACKNOWLEDGE);
		
		//开启手动签收模式
		Session session = connection.createSession(Boolean.FALSE, Session.CLIENT_ACKNOWLEDGE);
		
		//通过session创建destination对象，这是一个客户端用来生产数据的对象
		Destination destination = session.createQueue("queue1");
		
		//通过session对象创建消息的发送对象（生产者和消费者)MessageProducer/MessageConsumer
		MessageConsumer messageConsumer = session.createConsumer(destination);
		
		while (true) {
			TextMessage msg = (TextMessage) messageConsumer.receive();
			//CLIENT_ACKNOWLEDGE 模式下，手动签收，另起一个线程（tcp）去通知MQ服务 确认签收
			msg.acknowledge();
			if(msg == null){
				break;
			}
			System.out.println("收到内容："+msg.getText());
		}
		if(connection != null){
			connection.close();
		}
		System.out.println("消费完成");
	}
}
